import os
from PIL import Image

# 指定操作路径
path = r"D:\0_快速保存"

# 创建"jpg","old","gif"文件夹
save_folder = os.path.join(path, "jpg")
if not os.path.exists(save_folder):
    os.makedirs(save_folder)
old_folder = os.path.join(path, "old")
if not os.path.exists(old_folder):
    os.makedirs(old_folder)
gif_folder = os.path.join(path,"gif")
if not os.path.exists(gif_folder):
    os.makedirs(gif_folder)

# 遍历目录下的文件和文件夹
for filename in os.listdir(path):
    frames = 0
    filepath = os.path.join(path, filename)
    if os.path.isfile(filepath):
        # 获取文件扩展名
        ext = os.path.splitext(filepath)[1].lower()
        # 如果是gif文件，检查帧数是否为1
        if ext == ".gif":
            with Image.open(filepath) as img:
                # 获取帧数
                frames = img.n_frames
            if frames > 1:
                try:
                    os.rename(filepath, os.path.join(gif_folder, filename))
                except FileNotFoundError:
                    print(f"文件 {filename} 不存在")
                except FileExistsError:
                    print(f"文件 {filename} 已经存在于目标文件夹中")
                except Exception as e:
                    print(f"重命名文件 {filename} 出错，错误信息为：{e}")
        # 如果是其他图片文件或者帧数为1，则转换为JPEG格式
        if ext in ['.jpg', '.jpeg', '.png', '.bmp', '.webp'] or frames == 1:
            with Image.open(filepath) as img:
                # 转换为JPEG格式，质量80
                save_path = os.path.join(save_folder, "{}.jpg".format(os.path.splitext(filename)[0]))
                img.convert("RGB").save(save_path, optimize=True, progressive=True, quality=80)
                print("已转换：", filename)
            # 移动转换过的图片到"old"文件夹
            try:
                os.rename(filepath, os.path.join(old_folder, filename))
            except FileNotFoundError:
                print(f"文件 {filename} 不存在")
            except FileExistsError:
                print(f"文件 {filename} 已经存在于目标文件夹中")
            except Exception as e:
                print(f"重命名文件 {filename} 出错，错误信息为：{e}")
